require 'point'

RADIAN = 57.2957795
class Vector
  attr_accessor :length
  attr_accessor :angle
  attr_accessor :point
  
  alias :l :length
  alias :l= :length=
  alias :a :angle
  alias :a= :angle=
  alias :p :point
  alias :p= :point=
  
  def initialize(length = nil, angle = nil)
    unless length.nil?
      if length.is_a?(Point) or length.is_a?(Array)
        @point = Point.new(length)
      else
        @length = length
        @angle = angle
      end
    else
      @length = 0
      @angle = 0
    end
  end
  
  def angle=(val)
    @point = nil
    @angle = val
  end
  
  def angle
    if @angle.nil?
      x = @point.x.to_f
      y = @point.y.to_f
      
      if x == 0 and y == 0
        @angle = 0
      elsif x == 0 and y > 0
        @angle = 0
      elsif x > 0 and y == 0
        @angle = 90
      elsif x == 0 and y < 0
        @angle = 180
      elsif x < 0 and y == 0
        @angle = 270
      else
        angle_deg = Math.atan(y / x) * RADIAN
        @angle = angle_deg.round
        
        # Compensate for quadrants
        @angle = @angle * -1 if @angle < 0
        if x > 0 and y > 0
          # Do nothing
        elsif x > 0 and y < 0
          @angle += 90
        elsif x < 0 and y < 0
          @angle += 180
        elsif x < 0 and y > 0
          @angle += 270
        end
      end
    end
    
    @angle
  end
  
  def length=(val)
    @point = nil
    @length = val
  end
  
  def length
    if @length.nil?
      x = @point.x.to_f
      y = @point.y.to_f
      
      @length = Math.sqrt((x*x) + (y*y))
    end
    
    @length
  end
  
  def point=(val)
    @length = nil
    @angle = nil
    @point = val
  end
  
  def point
    if @point.nil?
      x = @length.to_f * Math.cos(@angle.to_f / RADIAN)
      y = @length.to_f * Math.sin(@angle.to_f / RADIAN)
      @point = Point.new(x, y)
    end
    
    @point
  end
end